package cn.cnsy123.shorturls.business.service.impl;

import java.nio.charset.StandardCharsets;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.cnsy123.shorturls.api.controller.param.SysSqlExecuteLogInsertParam;
import cn.cnsy123.shorturls.api.controller.vo.BaseResponse;
import cn.cnsy123.shorturls.business.entity.SysSqlExecuteLog;
import cn.cnsy123.shorturls.business.exception.BusinessException;
import cn.cnsy123.shorturls.business.mapper.SysSqlExecuteLogMapper;
import cn.cnsy123.shorturls.business.service.SysSqlExecuteLogService;
@Service
public class SysSqlExecuteLogServiceImpl implements SysSqlExecuteLogService {
    @Autowired
    private SysSqlExecuteLogMapper sysSqlExecuteLogMapper;

    @Override
    @Transactional(readOnly = false,propagation = Propagation.REQUIRES_NEW,rollbackFor = BusinessException.class)
    @Async
    public BaseResponse saveSqlExecutorLog(SysSqlExecuteLogInsertParam sysSqlExecuteLogInsertParam) {
        try {
            SysSqlExecuteLog record = new SysSqlExecuteLog();
            record.setOriginalSql(sysSqlExecuteLogInsertParam.getOriginalSql().getBytes(StandardCharsets.UTF_8));
            record.setExecuteTime(sysSqlExecuteLogInsertParam.getExecuteTime());
            record.setTakeUpTime(sysSqlExecuteLogInsertParam.getTakeUpTime());
            sysSqlExecuteLogInsertParam.getOriginalSql().trim().split(" ");
            record.setOperateType("");
            record.setCreateUser("系统管理员");
            record.setCreateTime(new Date(System.currentTimeMillis()));
            int flag = sysSqlExecuteLogMapper.insertSelective(record);
            return flag > 0 ? new BaseResponse(200, "保存执行sql成功"):new BaseResponse(100,"保存执行sql失败");
        } catch (Exception e) {
            throw new BusinessException(e);
        }
    }

}
